/*****录屏记录*****/
<template>
	<div id="screenRecord">
		<Row style="margin:16px 0;">
			<Select filterable v-model="querySessionInfo.userId" placeholder="请选择用户" @on-change="getConnectAllHistories" transfer style="width:150px;margin-right:15px;">
				<Option value="all">请选择用户</Option>
				<Option v-for="(member,index) in projectGroupMemberList" :key="index" :value="member.userId" :title="member.userName">{{member.userName}}</Option>
			</Select>
			<Page :total="sessionTotal" show-total show-elevator @on-change="changeSessionPage" style="float:right;" v-show="sessionList.length > 0" />
		</Row>
		<!--<Table stripe :columns="sessionCol" :data="sessionList"></Table>-->
		<TableList :columns="sessionCol" :data="sessionList"></TableList>
		<!-- 预览视图tab6 -->
		<Modal v-model="screenRecordModal" title="录屏回放" footer-hide :width="1366" @on-cancel="cancelModal()">
			<!-- Display -->
			<div id="player">
				<div id="display" style="overflow: hidden;">
					<!--<div class="notification-container">
	                    <div class="seek-notification">
	                        <p>
	                            Seek in progress...
	                            <button id="cancel-seek">Cancel</button>
	                        </p>
	                    </div>
	                </div>-->
				</div>
				<!-- Player controls -->
				<div class="controls">
					<button id="play-pause" class="ivu-btn ivu-btn-default ivu-btn-small">播放</button>
					<!--<button id="live">Live</button>-->
					<input id="position-slider" type="range">
					<span id="position">00:00</span>
					<span>/</span>
					<span id="duration">00:00</span>
				</div>
			</div>
		</Modal>
	</div>
</template>

<script>
	import Guacamole from '@/assets/minejs/all.min'
	import {
		getSessions,
		getSessionsRecord,
		delSession
	} from '@/api/drill'
	import cookieUse from '@/libs/cookie.js'
	import {
		getuserinstance
	} from '@/api/access_new'
	export default {
		name: 'screenRecord',
		props: ['type'], //接受演练竞赛类型
		components: {
		
		},
		data() {
			return {
				routeParams: {
					id: this.$route.query.id,
					prjid: this.$route.query.prjid
				},
				projectId: this.$route.query.prjid,
				//录屏文件记录
				screenRecordList: [],
				screenRecordModal: false,
				//会话
				querySessionInfo: {
					pageIndex: 1,
					pageSize: 10,
					projectId: this.$route.query.prjid,
					userType: 'experimenter',
					userId: 'all'
				},
				sessionList: [],
				sessionTotal: 0,
				sessionCol: [{
						title: '虚拟机',
						key: 'name',
						placement: 'top-left',
						tooltip:true,
						width:240
					},
			        { 
			          	title: '团队名称',  
			          	key: 'teamName',
						width: 120,
			          	render:(h,params) => {
			          		if(this.projectGroupMemberList.length > 0){
								let name = this.projectGroupMemberList.filter(user => user.userId == params.row.userId)[0].accessGroupName
								return h('Tooltip',{
									'class':'tableTooltip',
									props:{
										maxWidth:400,
										placement:'top',
										triggle:'hover',
										transfer:true
									}
								},[
									h('p',{
										'class':'showContent',
										style:{
											maxWidth:'120px'
										}
									}, name),
									h('div',{
										'class':'tooltipContent',
										slot:'content'
									}, name)
								])
			          		}else{
			          			return h('span','')
			          		}
						}
			        },
					{
						title: '用户名',
						key: 'userName',
						tooltip:true,
						width:120
					}, {
						title: '协议',
						key: 'protocol',
						width: 60
					}, {
						title: 'Ip',
						key: 'ip',
						width: 112
					}, {
						title: '状态',
						key: 'status',
						width: 100,
						render: (h, params) => {
							let obj = this.paserStatus(params.row.status)
							return h('span', {
								style: {
									color: obj.color
								}
							}, obj.text);
						}
					}, {
						title: '连接时间',
						key: 'connectTime'
					},
					//          { title: 'fileSize',  key: 'fileSize'},
					{
						title: '操作',
						key: 'action',
						align: 'center',
						width: 350,
						placement: 'top-right',
						action: true,
						opList:[
							{
								txt:'录屏回放',
								on: {
									click: (data) => {
										this.modal6 = true;
										this.guac = '';
										this.initPlayer(data.id);
									}
								}
							},
							{
								txt:'删除',
								on: {
									click: (data) => {
										this.delSession(data.id);
									}
								}
							}
						],
						// render: (h, params) => {
						// 	return h('div', [
						// 		h('Button', {
						// 			props: {
						// 				type: 'info',
						// 				size: 'small'
						// 			},
						// 			style: {
						// 				marginRight: '5px'
						// 			},
						// 			on: {
						// 				click: () => {
						// 					this.modal6 = true;
						// 					this.guac = '';
						// 					this.initPlayer(params.row.id);
						// 				}
						// 			}
						// 		}, '录屏回放'),
						// 		h('Poptip', {
						// 			props: {
						// 				confirm: true,
						// 				'ok-text': "确定",
						// 				'cancel-text': "取消",
						// 				type: 'error',
						// 				size: 'large',
						// 				title: '你确定要删除吗?',
						// 				transfer: true
						// 			},
						// 			on: {
						// 				'on-ok': () => {
						// 					this.delSession(params.row.id);
						// 				}
						// 			}
						// 		}, [
						// 			h('Button', {
						// 				props: {
						// 					type: 'error',
						// 					size: 'small'
						// 				},
						// 				style: {},
						// 			}, '删除')
						// 		])
						// 	]);
						// }
					}
				],
				queryGroupMemberInfo: {
					testId: this.$route.query.id,
					pageIndex: 1,
					pageSize: 1000000
				},
				projectGroupMemberList: []

			}
		},
		filters: {

		},
		watch: {

		},
		beforeDestroy() {

		},
		mounted() {
			this.getConnectAllHistories();
			this.getProjectGroupMember();
		},
		methods: {
			// 状态转义为包含颜色，文本的对象，用于组件使用
			paserStatus(status) {
				switch(status) {
					case 'disconnected': return { text: '已断开', color: '#ed4014' }
					case 'unconnected': return { text: '未连接', color: '#2db7f5' }
					case 'connected': return { text: '已连接', color: '#19be6b' }
				}
			},
			getConnectAllHistories() {
				let params = JSON.parse(JSON.stringify(this.querySessionInfo));
				if(params.userId == 'all') {
					delete params.userId
				}
				params.status = 'disconnected'
				params.enableRecordScreen = true
				params.enableRecordScreenPlayback = true
				getSessions(params).then(data => {
					if(data.code == 1) {
						this.sessionList = data.data.items;
						this.sessionTotal = data.data.total;
					} else {
						this.$Message.error(data.message);
					}
				})
			},
			getTeams() {
				let _this = this;
				axios({
					url: 'director/attack/teams?projectId=' + _this.nowUsePrjId,
					method: 'get'
				}).then(function(response) {
					if(response.code != '1') {
						_this.$Message.warning(response.message);
					} else {
						_this.tab7TbData = response.data;

					}
				});
			},
			getSessionsRecord(id) {
				getSessionsRecord(id).then(data => {
					if(data.code == 1) {
						this.screenRecordList = data.data.file;
					} else {
						this.screenRecordList = [];
						this.$Message.error(data.message ? data.message : '获取录屏记录失败');
					}
				})
			},
			changeSessionPage(page) {
				this.querySessionInfo.pageIndex = page;
				this.getConnectAllHistories();
			},
			getProjectGroupMember() {
				getuserinstance(this.queryGroupMemberInfo).then(data => {
					if(data.code == 1) {
						this.projectGroupMemberList = data.data.items.filter(item => item.inviterName != '内部服务用户');
					} else if(data.code == -2) {
						this.projectGroupMemberList = [];
					} else {
						this.$Message.warning(data.message);
					}
				})
			},
			initPlayer(sessionId) {
				/**
				 * The URL of the Guacamole session recording which should be played back.
				 *
				 * @constant
				 * @type String
				 */
				this.screenRecordModal = true;
				var token = cookieUse.getCookie('desig-token'); //this.GetQueryString("token");
				// var token = "02f3a158b81347dba1526d485389c614";
				document.cookie = 'token=' + token
				if(!token) {
					//alert('文件为空');
					this.$Message.error('文件为空');
					this.screenPlaybackMd = false;
					return;
				}
				let url = location.host;
				//          let crheetian = "http://172.18.100.4:18769/"
				let crheetian = `/api`
					// console.log(token)
				var param = 'token=' + token;
				// var RECORDING_URL = '/home/access/recording/8d7b998856a04642b760f24cece582d7.guac';
				var RECORDING_URL = crheetian + '/access/sessions/' + sessionId + "/recording";
				// var RECORDING_URL = '/api/access/record?id='+ this.currRecordId;

				/**
				 * The element representing the session recording player.
				 *
				 * @type Element
				 */
				var player = document.getElementById('player');

				/**
				 * The element which will contain the recording display.
				 *
				 * @type Element
				 */
				var display = document.getElementById('display');

				/**
				 * Play/pause toggle button.
				 *
				 * @type Element
				 */
				var playPause = document.getElementById('play-pause');
				// playPause.trigger('click');

				var live = document.getElementById('live');

				/**
				 * Button for cancelling in-progress seek operations.
				 *
				 * @type Element
				 */
				//          var cancelSeek = document.getElementById('cancel-seek');

				/**
				 * Text status display indicating the current playback position within the
				 * recording.
				 *
				 * @type Element
				 */
				var position = document.getElementById('position');

				/**
				 * Slider indicating the current playback position within the recording,
				 * and allowing the user to change the playback position.
				 *
				 * @type Element
				 */
				var positionSlider = document.getElementById('position-slider');

				/**
				 * Text status display indicating the current length of the recording.
				 *
				 * @type Element
				 */
				var duration = document.getElementById('duration');

				/**
				 * The tunnel which should be used to download the Guacamole session
				 * recording.
				 *
				 * @type Guacamole.Tunnel
				 */
				var tunnel = new Guacamole.StaticHTTPTunnel(RECORDING_URL);
				//var tunnel = new Guacamole.WebSocketTunnel(RECORDING_URL);

				/**
				 * Guacamole.SessionRecording instance to be used to playback the session
				 * recording.
				 *
				 * @type Guacamole.SessionRecording
				 */
				var recording = new Guacamole.SessionRecording(tunnel);
				this.recording = recording;
				/**
				 * The Guacamole.Display which displays the recording during playback.
				 *
				 * @type Guacamole.Display
				 */
				var recordingDisplay = recording.getDisplay();

				/**
				 * Converts the given number to a string, adding leading zeroes as necessary
				 * to reach a specific minimum length.
				 *
				 * @param {Numer} num
				 *     The number to convert to a string.
				 *
				 * @param {Number} minLength
				 *     The minimum length of the resulting string, in characters.
				 *
				 * @returns {String}
				 *     A string representation of the given number, with leading zeroes
				 *     added as necessary to reach the specified minimum length.
				 */
				var zeroPad = function zeroPad(num, minLength) {

					// Convert provided number to string
					var str = num.toString();

					// Add leading zeroes until string is long enough
					while(str.length < minLength)
						str = '0' + str;

					return str;

				};

				/**
				 * Converts the given millisecond timestamp into a human-readable string in
				 * MM:SS format.
				 *
				 * @param {Number} millis
				 *     An arbitrary timestamp, in milliseconds.
				 *
				 * @returns {String}
				 *     A human-readable string representation of the given timestamp, in
				 *     MM:SS format.
				 */
				var formatTime = function formatTime(millis) {

					// Calculate total number of whole seconds
					var totalSeconds = Math.floor(millis / 1000);

					// Split into seconds and minutes
					var seconds = totalSeconds % 60;
					var minutes = Math.floor(totalSeconds / 60);

					// Format seconds and minutes as MM:SS
					return zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);

				};

				// Add playback display to DOM
				display.appendChild(recordingDisplay.getElement());

				// Begin downloading the recording
				console.log(param)
				recording.connect(param);

				// If playing, the play/pause button should read "Pause"
				recording.onplay = function() {
					playPause.textContent = '暂停';
				};

				// If paused, the play/pause button should read "Play"
				recording.onpause = function() {
					playPause.textContent = '播放';
				};

				// Toggle play/pause when display or button are clicked
				display.onclick = playPause.onclick = function() {
					if(!recording.isPlaying())
						recording.play();
					else
						recording.pause();
				};

				// Resume playback when cancel button is clicked
				//          cancelSeek.onclick = function cancelSeekOperation(e) {
				//              recording.play();
				//              player.className = '';
				//              e.stopPropagation();
				//          };

				// Fit display within containing div
				recordingDisplay.onresize = function displayResized(width, height) {

					// Do not scale if display has no width
					if(!width)
						return;

					// Scale display to fit width of container
					recordingDisplay.scale(display.offsetWidth / width);

				};

				// Update slider and status when playback position changes
				recording.onseek = function positionChanged(millis) {
					position.textContent = formatTime(millis);
					positionSlider.value = millis;
				};

				// 在五秒内计算如果时常没有变化就跳转到最后的时间

				// Update slider and status when duration changes
				recording.onprogress = function durationChanged(millis) {
					duration.textContent = formatTime(millis);
					positionSlider.max = millis;
					//console.log('获取到新消息');
					if(!recording.isPlaying()) {
						//console.log('获取到新消息，继续播放')
						recording.play();
					}

				};

				// Seek within recording if slider is moved
				positionSlider.onchange = function sliderPositionChanged() {

					console.log(positionSlider.value);
					// Request seek
					recording.seek(positionSlider.value, function seekComplete() {

						// Seek has completed
						player.className = '';

					});

					// Seek is in progress
					player.className = 'seeking';

				};

				//          live.onclick = function () {
				//
				//              // Request seek
				//              recording.seek(positionSlider.max, function seekComplete() {
				//
				//                  // Seek has completed
				//                  player.className = '';
				//
				//              });
				//
				//              // Seek is in progress
				//              player.className = 'seeking';
				//          }
			},
			cancelModal() {
				let display = document.getElementById("display");
				this.recording.pause();
				let childs = display.childNodes;
				for(let i = childs.length - 1; i >= 0; i--) {
					if(childs[i].className == 'notification-container') {
						return;
					} else {
						display.removeChild(childs[i]);
					}
				};
			},
			delSession(id) {
				delSession(id).then(data => {
					if(data.code == 1) {
						this.getConnectAllHistories();
						this.$Message.info('删除成功');
					} else {
						this.$Message.error(data.message);
					}
				}).catch(error => {
					this.$Message.error('删除失败');
				})
			}
		}
	}
</script>

<style>
	.drillsTable .ivu-poptip-body {
		text-align: left !important;
	}
	
	.scenesHeader {
		margin-bottom: 16px;
	}
	
	.drillTables {
		min-height: 300px;
	}
	
	.drillsTable.ivu-table-wrapper {
		overflow: inherit;
	}
	
	.controls {
		display: flex;
		margin-top: 10px;
		align-items: center;
	}
	
	#position-slider {
		flex: 1 1 auto;
		margin: 0 10px;
	}
	
	#play-pause {}
</style>
<style scoped>
	.Titles {
		background: #eeeeee;
		margin: 16px auto;
		padding: 10px 0;
	}
	
	.targetHeader {
		/*padding: 10px;*/
		margin-bottom: 10px;
	}
	
	
</style>